
const jwt = require('jsonwebtoken')

const { JWT_SECRET } = require('../config/config.default')

const { tokenExpiredError, invalidToken, hasNotAdminPermission } = require('../constant/err.type')
// 验证用户是否登陆
const auth = async (ctx, next) => {
    // 解析出token
    const { authorization = '' } = ctx.request.header
    const token = authorization.replace('Bearer ', '')
    try {

        // 解析出用户信息
        const user = jwt.verify(token, JWT_SECRET)
        // 挂载到state
        ctx.state.user = user
    } catch (error) {
        switch (error.name) {
            case "TokenExpiredError":
                console.error("Token过期", error)
                return ctx.app.emit('error', tokenExpiredError, ctx)
            case "JsonWebTokenError":
                console.error("无效Token", error)
                return ctx.app.emit('error', invalidToken, ctx)
            default:
                console.error("登陆异常", error)
        }
    }

    // 验证token
    await next()
}
// 验证管理员权限
const hadAdminPermission = async (ctx, next) => {
    const { is_admin } = ctx.state.user
    if (!is_admin) {
        console.error("该用户没有管理员权限！")
        return ctx.app.emit('error', hasNotAdminPermission, ctx)
    }
    await next()
}
module.exports = {
    auth,
    hadAdminPermission
}